package com.chery.media.ui.play.hot

import androidx.lifecycle.LifecycleOwner
import com.chery.media.library.base.BaseViewModel
import com.chery.media.library.event.SingleLiveEvent
import com.chery.media.library.extend.asResponse
import com.chery.media.library.extend.toast
import com.chery.media.library.network.ResponseThrowable
import com.chery.media.network.model.MusicBean
import com.chery.media.utils.appRepository
import kotlinx.coroutines.flow.catch

class HotViewModel : BaseViewModel() {


    val hotMusicList = SingleLiveEvent<ArrayList<MusicBean>>()

    var page: Int = 1
        set(value) {
            field = value
            getHotMusicList()
        }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        page = 1
    }

    /**
     * 获取热门音乐列表
     */
    private fun getHotMusicList() {
        launch {
            val map = mutableMapOf<String, Any>()
            map["limit"] = "100"
            map["page"] = page
            launch {
                appRepository.getMusicData(map)
                    .asResponse()
                    .catch { if (it is ResponseThrowable) it.errMsg.toast() }
                    .collect {
                        it.records?.forEach {music ->
                            music.title = music.playPath?.substring(music.playPath!!.lastIndexOf("/") + 1, music.playPath!!.lastIndexOf(".")) ?: ""
                            music.playPath = "http://music.163.com/song/media/outer/url?id=317151.mp3"
                        }
                        hotMusicList.value = it.records ?: arrayListOf()
                    }
            }
        }
    }

}